<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button @click="getDataList(null,true)" type="success">查询全部</el-button>
        <el-button v-if="isAuth('pms:attrgroup:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button v-if="isAuth('pms:attrgroup:delete')" type="danger" @click="deleteHandle()"
                   :disabled="dataListSelections.length <= 0">批量删除
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      lazy
      :load="lazyLoad"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="attrGroupId"
        header-align="center"
        align="center"
        label="分组id">
      </el-table-column>
      <el-table-column
        prop="attrGroupName"
        header-align="center"
        align="center"
        label="组名">
      </el-table-column>
      <el-table-column
        prop="sort"
        header-align="center"
        align="center"
        label="排序">
      </el-table-column>
      <el-table-column
        prop="descript"
        header-align="center"
        align="center"
        label="描述">
      </el-table-column>
      <el-table-column
        prop="icon"
        header-align="center"
        align="center"
        label="组图标">
        <template slot-scope="slot">
          <img :src="hostPrefix+slot.row.icon" v-if="hostPrefix" alt="" style="width: 100px;">
        </template>
      </el-table-column>
      <el-table-column
        prop="catelogId"
        header-align="center"
        align="center"
        label="所属分类id">
        <template slot-scope="slot">
          <el-tag v-text="slot.row.categoryName"></el-tag>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="associateAttrHandler(scope.row.attrGroupId)">关联属性</el-button>
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.attrGroupId)">修改</el-button>
          <el-button type="text" size="small" @click="deleteHandle(scope.row.attrGroupId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <!--    关联属性-->
    <associate-attr-component v-if="associateAttrVisible" ref="associateAttrRef"></associate-attr-component>
  </div>
</template>

<script>
import AddOrUpdate from './attrgroup-add-or-update'
import attrGroupApi from '../../../../api/product/attrGroupApi'
import uploadToAiliOss from '../../../../api/uploadToAiliOss'
import associateAttrComponent from './associatedAttrList'

export default {
  name:'attrGroup-auto-generate',
  props: ['hub'],
  data () {
    return {
      dataForm: {
        key: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      categoryId: null,
      hostPrefix: null,
      associateAttrVisible: false,
    }
  },
  components: {
    AddOrUpdate, associateAttrComponent
  },
  activated () {
    //this.getDataList()
  },
  methods: {

    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true

      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.attrGroupId
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/pms/attrgroup/deleteBatch'),
          method: 'put',
          data: this.$http.adornData(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    getDataList (categoryId, globalSearch) {

      let attrGroupName = null

      let attrGroupId = null

      let key = this.dataForm.key

      if (categoryId) {
        this.categoryId = categoryId
      }

      if (/^[0-9]+$/.test(key)) {
        console.log('用户输入的是attr_group_id')
        attrGroupId = key
      } else if (key.length > 0) {
        console.log('用户输入的是组的名字')
        attrGroupName = key
      }

      attrGroupApi.getAttrGroupPaginationByCondition(
        globalSearch ? null : this.categoryId,
        this.pageIndex, this.pageSize, attrGroupName, attrGroupId).then(({data}) => {

        //console.log(data)
        if (data && data.code === 0) {
          this.dataList = data.page.list

          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false

        //console.log('属性分组数据是', this.dataList)

        /*        this.dataList.forEach((g, index) => {
                  categoryApi.getCategoryInfoByCategoryId(g.catelogId).then(({data}) => {

                    let {categoryName} = this.dataList[index];
                    let c = categoryName;
                    categoryName = data.category.name
                  })

                })*/
      })

    },

    getHostAddressPrefix () {
      uploadToAiliOss.getHostAddress().then(({data}) => {
        this.hostPrefix = data.host + '/'
      })
    },
    /**
     * 加载子节点数据的函数，lazy 为 true 时生效，函数第二个参数包含了节点的层级信息
     * */
    lazyLoad (ow, treeNode, resolve) {
      console.log('懒加载', ow, treeNode, resolve)
    },

    associateAttrHandler (attrGroupId) {
      this.associateAttrVisible = true
      this.$nextTick(() => {
        this.$refs.associateAttrRef.dialogTableVisible = true;
        this.$refs.associateAttrRef.getRelationList(attrGroupId);
      })
    }

  },
  /**
   * 模版创建完成之后就去注册中心绑定事件
   * */
  mounted () {
    this.getHostAddressPrefix()
    this.getDataList(null, true)
  },
  watch: {
    hub (val) {
      // console.log('attrgroup中的hub更新了', val)
      if (val) {
        /**
         * @Param1 要绑定事件的名称
         * @Param2 本事件触发时，执行的方法；val为传递过来的参数
         * */
        val.$on('change-category-id', (data, categoryNode, nodeSelf) => {
          console.log('兄弟节点attr-group-auto-generate收到要查询的节点', categoryNode)
          if (categoryNode.level === 3) {

            this.getDataList(categoryNode.data.catId)
          }
        })
      }
    }
  }
}
</script>
